<template>
  <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片布局 -->
    <el-card>
      <el-button type="primary" @click="addfenleidialog">添加分类</el-button>
      <!-- 商品分类列表 -->
      <el-table :data="categorieslist" row-key="cat_id" stripe border :tree-props="{children:'children',hasChildren:'cat_level!==2'}">
           <el-table-column type="index"></el-table-column>
           <el-table-column label="商品名称" prop="cat_name">
           </el-table-column>
           <el-table-column label="是否有效" prop="cat_deleted">
              <template v-slot="scope">
                <i :class="scope.row.cat_deleted===false? 'el-icon-success':'el-icon-error'"></i>
              </template>
           </el-table-column>
           <el-table-column label="排序" prop="cat_level">
                <template v-slot="scope">
                    <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
                    <el-tag type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
                    <el-tag type="warning" v-else>三级</el-tag>
                </template>
           </el-table-column>
            <el-table-column label="操作" width="180px">
            <template v-slot="scope">
             <el-button v-model="scope.row" type="primary" icon="el-icon-edit" size="mini" @click="showeditcatedialog(scope.row.cat_id)">编辑</el-button>
             <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletecatedialogsure(scope.row.cat_id)">删除</el-button>
            </template>
          </el-table-column>
      </el-table>
    <!-- 添加分页 -->
    <el-pagination
      @size-change="handlecateSizeChange"
      @current-change="handlecateCurrentChange"
      :current-page="categoriesqueryinfo.pagenum"
      :page-sizes="5"
      :page-size="categoriesqueryinfo.pagesize"
      layout="total, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" v-model="showaddfenleidialogvisible" @close="addfenleidialogreset">
      <el-form :model="addfenleiForm" :rules="addfenleiFormrules" ref="addfenleiFormref" label-width="70px">
        <el-form-item label="分类名称" prop="cat_name" label-width="100px">
          <el-input v-model="addfenleiForm.cat_name">
          </el-input>
        </el-form-item>
        <!-- options指定数据源  props配置对象 -->
        <el-form-item label="父级分类" label-width="100px">
          <el-cascader :options="parentfenleilist" :props="cascaderprops" @change="parenthandleChange" v-model="selectkeys" clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="showaddfenleidialogvisible = false">取 消</el-button>
          <el-button type="primary" @click="addfenleiformsure">确 定</el-button>
        </span>
        </template>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog title="编辑分类" v-model="showeditcatedialogvisible">
      <el-form :model="editfenleiForm" :rules="editfenleiFormrules" ref="editfenleiFormref" label-width="70px">
        <el-form-item label="分类名称" prop="cat_name" label-width="100px">
          <el-input v-model="editfenleiForm.cat_name">
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="showeditcatedialogvisible = false">取 消</el-button>
        <el-button type="primary" @click="editfenleiformsure">确 定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //   请求商品分类的参数
      categoriesqueryinfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 商品分类列表
      categorieslist: [],
      // 总数据数
      total: 0,
      showaddfenleidialogvisible: false,
      addfenleiForm: {
        cat_name: '',
        // 默认为一级分类
        cat_level: 0,
        cat_pid: 0
      },
      addfenleiFormrules: {
        cat_name: [
          { required: true, message: '请输入分类名', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
        ]
      },
      editfenleiFormrules: {
        cat_name: [
          { required: true, message: '请输入分类名', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
        ]
      },
      showeditcatedialogvisible: false,
      // 父级分类列表
      parentfenleilist: [
      ],
      // 级联选择器的配置对象
      cascaderprops: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: 'true'
      },
      // 选择的父类id数组
      selectkeys: [],
      editfenleiForm: ''
    }
  },
  created() {
    this.getcategoriesList()
  },
  methods: {
    //   获取商品分类列表
    async getcategoriesList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.categoriesqueryinfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      this.categorieslist = res.data.result
      this.total = res.data.total
      console.log(this.categorieslist)
    },
    // 监听size改变
    handlecateSizeChange(newsize) {
      this.categoriesqueryinfo.pagesize = newsize
      this.getcategoriesList()
    },
    // 监听页码值改变
    handlecateCurrentChange(newnum) {
      this.categoriesqueryinfo.pagenum = newnum
      this.getcategoriesList()
    },
    // 监听添加分类按钮变化
    addfenleidialog() {
      // 获取父级名称
      this.parentfenleilistquery()
      this.showaddfenleidialogvisible = true
    },
    // 确认提交添加分类表单
    addfenleiformsure() {
      this.$refs.addfenleiFormref.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addfenleiForm)
        if (res.meta.status !== 201) return this.$message.error('增加分类失败')
        this.$message.success('增加分类成功')
        this.getcategoriesList()
        this.showaddfenleidialogvisible = false
      })
    },
    // 添加分类对话框关闭时进行清空
    addfenleidialogreset() {
      this.$refs.addfenleiFormref.resetFields()
      this.selectkeys = []
      this.addfenleiForm.cat_level = 0
      this.addfenleiForm.cat_pid = 0
    },
    // 展示编辑对话框,获取数据
    async showeditcatedialog(id) {
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) return this.$message.error('请求失败')
      this.editfenleiForm = res.data
      console.log(this.editfenleiForm)
      this.showeditcatedialogvisible = true
    },
    // 获取父级分类列表parentfenleilistquery
    async parentfenleilistquery() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级商品分类列表失败')
      }
      this.parentfenleilist = res.data
      console.log(this.parentfenleilist)
    },
    // 监听父分类的变化
    parenthandleChange() {
      console.log(this.selectkeys)
      // 父级分类id
      if (this.selectkeys.length > 0) {
        this.addfenleiForm.cat_pid = this.selectkeys[this.selectkeys.length - 1]
        // 当前分类等级
        this.addfenleiForm.cat_level = this.selectkeys.length
      } else {
        this.addfenleiForm.cat_pid = 0
        this.addfenleiForm.cat_level = 0
      }
    },
    // 提交编辑后的内容
    editfenleiformsure() {
      this.$refs.editfenleiFormref.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.editfenleiForm.cat_id}`, { cat_name: this.editfenleiForm.cat_name })
        if (res.meta.status !== 200) return this.$message.error('编辑失败')
        this.$message.success('编辑分类成功')
        this.getcategoriesList()
        this.showeditcatedialogvisible = false
      })
    },
    // 删除确认
    async deletecatedialogsure(id) {
      const confirmresult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmresult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data: res } = await this.$http.delete('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除分类失败')
      }
      console.log(res.data)
      this.getcategoriesList()
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-cascader{
  width: 100%;
}
</style>
